package com.taiji.dicom4cloud.smart.camera;

import com.alibaba.fastjson.JSONObject;
import com.taiji.dicom4cloud.common.core.utils.FileUtil;
import com.taiji.dicom4cloud.common.security.utils.SecurityUtils;
import com.taiji.dicom4cloud.smart.model.entity.RfidRecord;
import com.taiji.dicom4cloud.smart.rfid.config.MqttGatewayService;
import com.taiji.dicom4cloud.smart.service.AlarmRecordService;
import com.taiji.dicom4cloud.smart.service.FtpFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;

/**
 * @ClassName FtpFileListener
 * @Description
 * @Author HX
 * @Date 2021/9/27 14:26
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class FtpFileListener implements FileAlterationListener {


    private final FtpFileService ftpFileService;

    private final AsyncTaskService asyncTaskService;

    private final AlarmRecordService alarmRecordService;

    private final MqttGatewayService mqttGatewayService;

    private Map<String, Object> map;

    public void init(Map<String, Object> stringObjectMap){
        map = stringObjectMap;
    }

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {}

    /**
     * 监控目录中创建一个目录时触发
     * @param file
     */
    @Override
    public void onDirectoryCreate(File file) {}

    /**
     * 监控目录中目录发生改变触发
     * @param file
     */
    @Override
    public void onDirectoryChange(File file) {}

    /**
     * 监控目录中目录发生删除触发
     * @param file
     */
    @Override
    public void onDirectoryDelete(File file) { }

    /**
     * 监控目录中创建文件时触发
     * @param file
     */
    @Override
    public void onFileCreate(File file) {
        String filePath = file.getParentFile().getPath();
        String temp[] = filePath.split(Matcher.quoteReplacement(File.separator));

        String orgId = SecurityUtils.getUser().getOrgId();

        //预警时，必须开启录像
        if(file.getName().endsWith(".dav")){
            //不走大华云预警接口回调，走云平台监听
            if(Integer.parseInt(map.get("use_dh_cloud").toString())==1){
                log.info("开始写入预警记录");
                String deviceId = temp[temp.length - 1];
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msgType","custom");//todo...从图片名中解析预警类型
                jsonObject.put("messageId","");
                jsonObject.put("time", LocalDateTime.now());
                jsonObject.put("deviceId",deviceId);
                RfidRecord record = alarmRecordService.saveCameraData(jsonObject);
                mqttGatewayService.send2Mqtt("alarm.rfid", JSONObject.toJSONString(record));
                ftpFileService.saveFtpFile(file,record.getId());
                log.info("预警入库:{},{},{}",file.getName(),file.getAbsolutePath(),file.getParentFile().getPath());
                //按机构生成转码目录
                String outFilePath = map.get("mp4_dir").toString()+File.separator+orgId+File.separator+temp[temp.length - 1];
                if(FileUtil.createDir(outFilePath)){
                    String outPath = outFilePath+File.separator+file.getName().replace(".dav",".mp4");
                    CompletableFuture<String> future = asyncTaskService.videoConvert(file.getAbsolutePath(),outPath);
                    future.whenComplete((result,e)->{
                        //转换成功，写入转换后的地址
                        log.info("转换结果写入数据库：{}",file.getPath());
                        ftpFileService.saveTranPath(record.getId());
                        record.setCameraHlsUrl(outPath.replace(map.get("mp4_dir").toString(),"/mp4"));
                        alarmRecordService.updateById(record);
                    });

                    String imagePath = outPath.replace(".mp4",".jpg");
                    CompletableFuture<String> future2 = asyncTaskService.videoScreenShot(file.getAbsolutePath(),imagePath);
                    future2.whenComplete((result,e)->{
                        record.setCameraCaptureUrl(imagePath.replace(map.get("mp4_dir").toString(),"/mp4"));
                        alarmRecordService.updateById(record);
                    });
                }
            }
        }
    }

    /**
     * 监控目录中改变文件时触发
     * @param file
     */
    @Override
    public void onFileChange(File file) {
        //业务代码
//        log.info("监控目录中改变文件时触发:",file.getName());
    }

    /**
     * 监控目录中文件删除时触发
     * @param file
     */
    @Override
    public void onFileDelete(File file) {
        //业务代码
//        log.info("监控目录中文件删除时触发:",file.getName());
    }

    /**
     *
     * @param fileAlterationObserver
     */
    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {

    }
}
